package com.danco.training.zaneuskaya.repository.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.danco.training.zaneuskaya.domain.Job;
import com.danco.training.zaneuskaya.domain.User;
import com.danco.training.zaneuskaya.repository.JobDao;
/**
 * @author Zaneuskaya Aliaksandra
 *
 */
@Repository
public class JobDaoImpl extends AbstractHibernateDao<Job,Integer> implements JobDao{

	private static final String JOB_START_DATE = "jobStartDate";
	private static final String COMPANY_TITLE = "companyTitle";
	private static final String POSITION_JOB = "position";
	private static final String USER_JOB = "userJob";

	@Override
	public Job read(Integer PK) throws HibernateException {
		return super.read(Job.class, PK);
	}

	@Override
	public List<Job> readAll() throws HibernateException {
		
		return super.readAll(Job.class, JOB_START_DATE);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Job> findJobsByUser(User user) throws HibernateException{
		List<Job> jobs =  new ArrayList<Job>();
		Criteria criteria = getSession().createCriteria(Job.class);
		criteria.add(Restrictions.eq(USER_JOB, user));
		
		jobs =  modifyCriteria(criteria, JOB_START_DATE).list();
		return jobs;
	}



	@SuppressWarnings("unchecked")
	@Override
	public List<Job> findJobsByCompanyTitle(String title) throws HibernateException{
		List<Job> jobs =  new ArrayList<Job>();
		Criteria criteria = getSession().createCriteria(Job.class);
		criteria.add(Restrictions.like(COMPANY_TITLE, title));
		jobs =  modifyCriteria(criteria, JOB_START_DATE).list();
		return jobs;
	}

	@SuppressWarnings("unchecked")
	public List<Job> sortJobsByStartDateColumn(String column)throws HibernateException {
		List<Job> jobs =  new ArrayList<Job>();
		Criteria criteria = getSession().createCriteria(Job.class);
		criteria.addOrder(Order.desc(column));
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		jobs = criteria.list();
		return jobs;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Job> findJobsByUserPositionCompanyTitle(User user,
			String position, String title) throws HibernateException{
		List<Job> jobs =  new ArrayList<Job>();
		Criteria criteria = getSession().createCriteria(Job.class);
		criteria.add(Restrictions.eq(USER_JOB, user));
		criteria.add(Restrictions.like(POSITION_JOB, position));
		criteria.add(Restrictions.like(COMPANY_TITLE, title));
		jobs =  modifyCriteria(criteria, JOB_START_DATE).list();
		return jobs;
	}

	
}
